﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VersionComparer.Base;

namespace VersionComparer.DataModel
{
    public abstract class ComparableItemCreator: ComparableItem
    {
        protected abstract ComparableItem CreateFromValue (ItemId itemId);

        Dictionary<string, bool> processedItemNames = new Dictionary<string, bool>();
        
        public virtual ComparableItem Add(ItemId itemId)
        {
            lock (processedItemNames)
            {
                ComparableItem newItem = CreateFromValue(itemId);
                return newItem;
            }
        }
        public virtual int Order
        {
            get
            {
                return 100;
            }
        }
        public override ComparableItem Parent
        {
            get
            {
                return null;
            }
        }

        static ComparableItemCreator[] existingCreators;
        static object syncObject = new object();
        public static ComparableItemCreator[]  ExistingCreators
        {
            get
            {
                if (existingCreators == null)
                {
                    lock (syncObject)
                    {
                        if (existingCreators == null)
                        {
                            List<ComparableItemCreator> creators= new List<ComparableItemCreator> (AddInsManager.Current.GetObjectInstancesOfType<ComparableItemCreator>());
                            creators.Sort ( (x,y)=>x.Order.CompareTo ( y.Order ));
                            existingCreators = creators.ToArray ();
                        }
                    }
                }
                return existingCreators;

            }
        }
        public static void Clear()
        {
        }
        public static ComparableItem Create(ItemId itemid)
        {
            foreach (ComparableItemCreator creator in ExistingCreators)
            {
                var result = creator.Add(itemid);
                if ( result != null )
                    return result;
            }
            return null;
        }
        
    }
}
